//
//  JEHMoreViewController.m
//  SinaNews
//
//  Created by 蒋恩浩 on 15/12/3.
//  Copyright © 2015年 JEH. All rights reserved.
//

#import "JEHMoreViewController.h"

@interface JEHMoreViewController ()<UITableViewDataSource, UITableViewDelegate, JEHMoreTableViewCellDelegate, passOtherValueToMoreVC>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSMutableArray *dataSource;
@property (nonatomic, retain) JEHDataBaseHandle *handle;
@property (nonatomic, retain) NSMutableArray *nameArray;
@property (nonatomic, retain) UIView *headerView;
@property (nonatomic, retain) UILabel *headerTitle;

@end

@implementation JEHMoreViewController

- (void)dealloc {
    
    [_tableView release];
    [_dataSource release];
    [_nameArray release];
    _delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.view nightMode];
    [self.tableView nightMode];
    self.tabBarController.tabBar.alpha = 0;
    self.hidesBottomBarWhenPushed = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createTableView];
    [self createHeaderView];
    [self getData];
    [self getNameArrayFromDataBaseHandle];
    
#pragma mark - ReloadData
    NSNotificationCenter *centers = [NSNotificationCenter defaultCenter];
    [centers addObserver:self selector:@selector(receiveNotification:) name:@"ReloadData" object:nil];
}

#pragma mark - ReloadData
- (void)receiveNotification:(NSNotification *)notification {
    
    [self getNameArrayFromDataBaseHandle];
    [self.tableView reloadData];
}

- (void)getNameArrayFromDataBaseHandle {
    
    self.handle = [JEHDataBaseHandle shareDataBaseHandle];
    [self.handle openDataBase];
    [self.handle selectTitleArrayAllFromDataBase];
    self.nameArray = self.handle.nameArray.copy;
    [self.handle closeDataBase];
}

- (void)setTemp:(NSInteger)temp {
    if (_temp != temp) {
        _temp = temp;
    }
}

#pragma mark - getData
- (void)getData {
    
    self.dataSource = [NSMutableArray arrayWithCapacity:0];
    [JEHNetWorkTool getWithUrl:kNewsGETURL parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        
        if (result) {
            
            NSDictionary *dic = result[@"data"];
            NSArray *array = dic[@"list"];
            for (NSDictionary *dic in array) {
                
                JEHRootModel *root = [[JEHRootModel alloc] initWithDictionary:dic];
                [self.dataSource addObject:root];
                [root release];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self.tableView reloadData];
            });
        }
    } fail:^(NSError *error) {
        
//        NSLog(@"网不好¬¬¬¬等会");
    }];
}

#pragma mark - createTableView
- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20 + kHeaderHeight, self.view.width, self.view.height - 20 - kHeaderHeight + 44 - 5) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.bounces = NO;
    [_tableView registerClass:[JEHMoreTableViewCell class] forCellReuseIdentifier:@"JEHMoreTableViewCellIdentifier"];
    [_tableView registerClass:[JEHSubscribeTableViewCell class] forCellReuseIdentifier:@"JEHSubscribeTableViewCell"];
    [_tableView registerClass:[JEHRightTableViewCell class] forCellReuseIdentifier:@"UITableViewCellIdentifier"];
    [self.view addSubview:self.tableView];
}

#pragma mark - UITableViewDelegateMethod
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_dataSource) {
        
        return self.dataSource.count + 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        JEHMoreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHMoreTableViewCellIdentifier"];
        cell.temp = self.temp;
        cell.delegate = self;
        [cell nightMode];
        return cell;
    } else {
        JEHSubscribeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JEHSubscribeTableViewCell"];
        if (indexPath.row - 1 < self.dataSource.count) {
            
            [cell nightMode];
            cell.rootModel = self.dataSource[indexPath.row - 1];
            cell.temp = indexPath.row - 1;
            
#pragma mark - MorePageSubscribeBlockMethod
            void (^passValues)(NSInteger) = ^(NSInteger value) {

                [self.tableView reloadData];
            };
            cell.passValue = passValues;
            return cell;
        }
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCellIdentifier"];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        
        CGFloat height = (((self.nameArray.count + 1) % 3 == 0) ? ((self.nameArray.count + 1) / 3 * (30 + 15) - 15) : (((self.nameArray.count + 1) / 3 + 1) * (30 + 15) - 15));
        return height + 80;
    } else {
        return 100;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return kHeaderHeight + 10;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(10, 20, self.view.width, kHeaderHeight + 10)];
    myView.backgroundColor = [UIColor whiteColor];
    [myView nightMode];
    
    UILabel *leftLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 15, 70, 20)];
    leftLabel.text = @"频道切换";
    [myView addSubview:leftLabel];
    [leftLabel nightMode];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, leftLabel.bottom + 4, leftLabel.width, 1)];
    lineView.backgroundColor = [UIColor redColor];
    [myView addSubview:lineView];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(myView.width - 40, 15, 30, kHeaderHeight - 10);
    [rightButton setTitle:@"管理" forState:UIControlStateNormal];
    [rightButton setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(managementButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [myView addSubview:rightButton];
    return myView;
}

#pragma mark - passOtherValueToMoreVC
- (void)passOtherValueToMoreVC:(NSInteger)temp {
    
    if (temp < self.dataSource.count- 1) {
        
        JEHRootModel *root = self.dataSource[temp];
        [self.dataSource removeObjectAtIndex:temp];
        [self.tableView removeFromSuperview];
        [self createTableView];
        [self.delegate passValueWithUrl:root.url withTitleName:root.name];
    }
}

#pragma mark - managementButtonAction
- (void)managementButtonAction:(UIButton *)sender {
    
    JEHManagementViewController *management = [[JEHManagementViewController alloc] init];
    [self.navigationController pushViewController:management animated:YES];
    [management release];
}

#pragma mark - createHeaderView
- (void)createHeaderView {
    
#warning headerView高度调不了，不变
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, kHeaderHeight + 20)];
    [_headerView release];
    [self.view addSubview:_headerView];
    
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, kHeaderHeight + 19, _headerView.width, 1)];
    topView.backgroundColor = [UIColor grayColor];
    topView.alpha = 0.3;
    [_headerView addSubview:topView];
    
    UIButton *backBotton = [UIButton buttonWithType:UIButtonTypeCustom];
    backBotton.frame = CGRectMake(0, 20, 50, kHeaderHeight);
    [backBotton setImage:[UIImage imageNamed:@"goBackButton"] forState:UIControlStateNormal];
    [backBotton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:backBotton];
    
    self.headerTitle = [[UILabel alloc] initWithFrame:CGRectMake(self.view.width / 2 - 20, 20, 40, kHeaderHeight)];
    [_headerTitle release];
    _headerTitle.text = @"更多";
    [_headerView addSubview:_headerTitle];
    [_headerTitle nightMode];
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [rightButton setTitle:@"新增" forState:UIControlStateNormal];
    rightButton.frame = CGRectMake(self.view.width - 40, 20, 30, kHeaderHeight);
    [rightButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(newAddButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:rightButton];
}

#pragma mark - rightButtpnAction
- (void)newAddButtonAction {
    
    if (_dataSource) {

        JEHSubscribeViewController *subscribe = [[JEHSubscribeViewController alloc] init];
        subscribe.subscribeDataSource = self.dataSource;
        subscribe.delegate = self;
        [self.navigationController pushViewController:subscribe animated:YES];
        [subscribe release];
    }
}

#pragma mark - backButtonAction
- (void)backButtonAction:(UIButton *)sender {

    [self changeContentOfSetWithPage:self.temp];
}

#pragma mark - changeContentOfSetWithPage
- (void)changeContentOfSetWithPage:(NSInteger)page {

    [self.delegate passValueWithItem:page];
    
    JEHNewsViewController *news = [self.navigationController.viewControllers objectAtIndex:0];
    [self.navigationController popToViewController:news animated:YES];
}

- (void)pushToNextPage {
    
    [self newAddButtonAction];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
